package spark.network.strategy;

import org.apache.log4j.Logger;
import spark.network.IConnections;
import spark.network.IPreLoginResponseResultListener;
import spark.network.NetworkConnection;
import spark.network.protocol.*;
import spark.utility.OutWrapper;

import java.util.Collection;

public class PreLoginResponseStrategy implements IProtocolHandleStrategy<PreLoginResponse> {
	private static Logger logger = Logger.getLogger(PreLoginResponseStrategy.class);

	private IPreLoginResponseResultListener preLoginResponseListener;
	private IConnections connections;

	public PreLoginResponseStrategy(IConnections connections) {
		this.connections = connections;
	}

	public void setPreLoginResponseListener(IPreLoginResponseResultListener preLoginResponseListener) {
		this.preLoginResponseListener = preLoginResponseListener;
	}

	@Override
	public void handle(PreLoginResponse packet, OutWrapper<Response> acknowledgement, Collection<Base> responses) {
		acknowledgement.value = new PreLoginResponseAck(packet);
		PreLogin preLogin = packet.getRequest();
		//if the response's validation did not match that of our request
		if(packet.getValidation() != preLogin.getValidation()) {
			logger.error("Received an invalid PreLoginResponse, original validation of " + preLogin.getValidation() + " was unmatched by the response's validation " + packet.getValidation());
			if(preLoginResponseListener != null) {
				preLoginResponseListener.preLoginFailed("Connection response contained an invalid validation.");
			}
			return;
		}

		if(!packet.getAccepted()) {
			logger.info("Server did not accept the PreLogin reason given: " + new String(packet.getMessage()));
			if(preLoginResponseListener != null) {
				preLoginResponseListener.preLoginFailed("Server denied connection. Reason: " + new String(packet.getMessage()));
			}
			return;
		}

		NetworkConnection server = connections.getConnection(NetworkConnection.SESSION_UNESTABLISHED);
		if(server == null) {
			logger.error("Could not fetch the server, it seems that a prelogin already occurred and a session was handed out");
			if(preLoginResponseListener != null) {
				preLoginResponseListener.preLoginFailed("Valid connection response received from server however no connection object for the server was found.");
			}
			return;
		}
		server.setSession(packet.getSession());
		server.setAddress(packet.getSource());
		if(preLoginResponseListener != null) {
			preLoginResponseListener.preLoginSucceeded();
		}
	}
}